package com.ly.gen.web;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.ly.gen.config.Constant;
import com.ly.gen.model.GenInfo;
import com.ly.gen.service.ConnsService;
import com.ly.gen.utils.CodeGeneratorUtil;
import com.ly.gen.utils.FileUtils;
import com.ly.gen.utils.FileZipUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Map;

@RestController
@RequestMapping("/code")
@Slf4j
public class CodeController {

    @Autowired
    private ConnsService connsService;

    @GetMapping("/gen")
    public void genCode(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        GenInfo genInfo = new JSONObject(params).toBean(GenInfo.class);
        Map<String, Object> conn = connsService.getConn(genInfo.getConnId());
        genInfo.setConnAddr(conn.get("conn_addr").toString());
        genInfo.setUserName(conn.get("user_name").toString());
        genInfo.setPassword(conn.get("password").toString());
        genInfo.setDriver(Constant.driverMap.get(conn.get("db_type")));
        String codePath = FileUtils.getDataPath() + File.separator + "code" + File.separator + IdUtil.getSnowflakeNextIdStr();
        CodeGeneratorUtil.genCode(genInfo, codePath);
        log.debug("code path: {}", codePath);
        FileZipUtil.exportZip(response, codePath, "code");

        File file = new File(codePath);
        try {
            FileUtil.del(file);
        }catch (Exception e){
            log.error("delete file[{}] error: {}", codePath, e.getMessage());
        }
    }
}
